<template>
  <div>
    <!-- 统计卡片区域 -->
    <ContentWrap>
      <el-row :gutter="16" class="mb-4">
        <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
          <SummaryCard
            title="总建筑数量"
            :value="statsData.totalCount"
            icon="ep:office-building"
            icon-color="bg-blue-100"
            icon-bg-color="text-blue-500"
          />
        </el-col>
        <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
          <SummaryCard
            title="正常建筑"
            :value="statsData.statusStats['正常'] || 0"
            icon="ep:select"
            icon-color="bg-green-100"
            icon-bg-color="text-green-500"
          />
        </el-col>
        <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
          <SummaryCard
            title="维修建筑"
            :value="statsData.statusStats['维修'] || 0"
            icon="ep:tools"
            icon-color="bg-orange-100"
            icon-bg-color="text-orange-500"
          />
        </el-col>
        <el-col :xl="6" :lg="6" :md="12" :sm="12" :xs="24">
          <SummaryCard
            title="平均楼层"
            :value="statsData.averageFloors"
            :decimals="1"
            icon="ep:sort"
            icon-color="bg-purple-100"
            icon-bg-color="text-purple-500"
            suffix="层"
          />
        </el-col>
      </el-row>
    </ContentWrap>

    <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="学校ID" prop="schoolId">
        <el-input
          v-model="queryParams.schoolId"
          placeholder="请输入学校ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="建筑物名称" prop="buildingName">
        <el-input
          v-model="queryParams.buildingName"
          placeholder="请输入建筑物名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="建筑物编码" prop="buildingCode">
        <el-input
          v-model="queryParams.buildingCode"
          placeholder="请输入建筑物编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="建筑类型" prop="buildingType">
        <el-select
          v-model="queryParams.buildingType"
          placeholder="请选择建筑类型"
          clearable
          class="!w-240px"
        >
          <el-option label="教学楼" value="教学楼" />
          <el-option label="实验楼" value="实验楼" />
          <el-option label="办公楼" value="办公楼" />
          <el-option label="宿舍楼" value="宿舍楼" />
          <el-option label="图书馆" value="图书馆" />
          <el-option label="体育馆" value="体育馆" />
          <el-option label="食堂" value="食堂" />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层数" prop="floorCount">
        <el-input
          v-model="queryParams.floorCount"
          placeholder="请输入楼层数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="具体位置" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入具体位置"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="管理员ID" prop="managerId">
        <el-input
          v-model="queryParams.managerId"
          placeholder="请输入管理员ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="正常" :value="0" />
          <el-option label="维修" :value="1" />
          <el-option label="停用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['ao:building:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['ao:building:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['ao:building:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 图表区域 -->
  <ContentWrap>
    <el-row :gutter="16" class="mb-4">
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <el-card shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-lg font-medium">建筑类型分布</span>
            </div>
          </template>
          <Echart :options="buildingTypeChartOptions" :height="350" />
        </el-card>
      </el-col>
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <el-card shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-lg font-medium">建筑状态分布</span>
            </div>
          </template>
          <Echart :options="buildingStatusChartOptions" :height="350" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="mb-4">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-lg font-medium">楼层分布统计</span>
            </div>
          </template>
          <Echart :options="floorDistributionChartOptions" :height="300" />
        </el-card>
      </el-col>
    </el-row>
  </ContentWrap>

  <!-- 建筑详情卡片区域 -->
  <ContentWrap>
    <div class="mb-4">
      <h3 class="text-lg font-medium mb-3">建筑详情</h3>
      <el-row :gutter="16">
        <el-col
          v-for="building in (showAllBuildings ? list : list.slice(0, 6))"
          :key="building.buildingId"
          :xl="4" :lg="6" :md="8" :sm="12" :xs="24"
          class="mb-4"
        >
          <el-card
            shadow="hover"
            class="building-card cursor-pointer transition-all duration-300"
            :class="getBuildingCardClass(building.status)"
            @click="openForm('update', building.buildingId)"
          >
            <div class="flex flex-col h-full">
              <!-- 建筑标题 -->
              <div class="flex items-center justify-between mb-2">
                <h4 class="text-base font-medium truncate flex-1">
                  {{ building.buildingName }}
                </h4>
                <el-tag
                  :type="getStatusTagType(building.status)"
                  size="small"
                >
                  {{ getStatusText(building.status) }}
                </el-tag>
              </div>

              <!-- 建筑信息 -->
              <div class="flex-1 space-y-2 text-sm text-gray-600">
                <div class="flex items-center">
                  <Icon icon="ep:office-building" class="mr-2 text-blue-500" />
                  <span>{{ building.buildingType }}</span>
                </div>
                <div class="flex items-center">
                  <Icon icon="ep:sort" class="mr-2 text-green-500" />
                  <span>{{ building.floorCount }}层</span>
                </div>
                <div class="flex items-center">
                  <Icon icon="ep:location" class="mr-2 text-orange-500" />
                  <span class="truncate">{{ building.address || '未设置' }}</span>
                </div>
                <div class="flex items-center">
                  <Icon icon="ep:key" class="mr-2 text-purple-500" />
                  <span>{{ building.buildingCode }}</span>
                </div>
              </div>

              <!-- 底部操作区域 -->
              <div class="mt-3 pt-2 border-t border-gray-100">
                <div class="flex items-center justify-between text-xs text-gray-500">
                  <span>管理员: {{ building.managerId }}</span>
                  <span>ID: {{ building.buildingId }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 查看更多按钮 -->
      <div class="text-center mt-4" v-if="list.length > 6">
        <el-button type="primary" plain @click="showAllBuildings = !showAllBuildings">
          {{ showAllBuildings ? '收起' : `查看全部 ${list.length} 个建筑` }}
        </el-button>
      </div>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="buildingId"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="建筑物ID" align="center" prop="buildingId" />
      <el-table-column label="学校ID" align="center" prop="schoolId" />
      <el-table-column label="建筑物名称" align="center" prop="buildingName" />
      <el-table-column label="建筑物编码" align="center" prop="buildingCode" />
      <el-table-column label="建筑类型（教学楼/实验楼/办公楼/宿舍楼）" align="center" prop="buildingType" />
      <el-table-column label="楼层数" align="center" prop="floorCount" />
      <el-table-column label="具体位置" align="center" prop="address" />
      <el-table-column label="管理员ID" align="center" prop="managerId" />
      <el-table-column label="建筑描述" align="center" prop="description" />
      <el-table-column label="状态（0正常 1维修 2停用）" align="center" prop="status" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.buildingId)"
            v-hasPermi="['ao:building:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.buildingId)"
            v-hasPermi="['ao:building:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

    <!-- 表单弹窗：添加/修改 -->
    <BuildingForm ref="formRef" @success="getList" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { BuildingApi, Building } from '@/api/ao/building'
import BuildingForm from './BuildingForm.vue'
import SummaryCard from '@/components/SummaryCard/index.vue'
import { Echart } from '@/components/Echart'
import { EChartsOption } from 'echarts'

/** 建筑物信息 列表 */
defineOptions({ name: 'Building' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Building[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  schoolId: undefined,
  buildingName: undefined,
  buildingCode: undefined,
  buildingType: undefined,
  floorCount: undefined,
  address: undefined,
  managerId: undefined,
  description: undefined,
  status: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BuildingApi.getBuildingPage(queryParams)
    list.value = data.list
    total.value = data.total
    // 计算统计数据
    calculateStats()
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BuildingApi.deleteBuilding(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除建筑物信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await BuildingApi.deleteBuildingList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Building[]) => {
  checkedIds.value = records.map((item) => item.buildingId);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BuildingApi.exportBuilding(queryParams)
    download.excel(data, '建筑物信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 统计数据
const statsData = ref({
  totalCount: 0,
  buildingTypeStats: {} as Record<string, number>,
  statusStats: {} as Record<string, number>,
  floorStats: {} as Record<string, number>,
  averageFloors: 0
})

// 控制显示所有建筑
const showAllBuildings = ref(false)

// 获取建筑卡片样式类
const getBuildingCardClass = (status?: number): string => {
  switch(status) {
    case 0:
      return 'border-l-4 border-l-green-500'
    case 1:
      return 'border-l-4 border-l-orange-500'
    case 2:
      return 'border-l-4 border-l-red-500'
    default:
      return 'border-l-4 border-l-gray-500'
  }
}

// 获取状态标签类型
const getStatusTagType = (status?: number): 'success' | 'warning' | 'danger' | 'info' => {
  switch(status) {
    case 0:
      return 'success'
    case 1:
      return 'warning'
    case 2:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status?: number): string => {
  switch(status) {
    case 0:
      return '正常'
    case 1:
      return '维修'
    case 2:
      return '停用'
    default:
      return '未知'
  }
}

// 建筑类型分布饼图配置
const buildingTypeChartOptions = computed<EChartsOption>(() => ({
  title: {
    text: '建筑类型分布',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'middle',
    itemGap: 12
  },
  series: [
    {
      name: '建筑类型',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: Object.entries(statsData.value.buildingTypeStats).map(([name, value]) => ({
        name,
        value,
        itemStyle: {
          color: getTypeColor(name)
        }
      }))
    }
  ]
}))

// 建筑状态分布柱状图配置
const buildingStatusChartOptions = computed<EChartsOption>(() => ({
  title: {
    text: '建筑状态分布',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: Object.keys(statsData.value.statusStats),
    axisTick: {
      alignWithLabel: true
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '建筑数量',
      type: 'bar',
      barWidth: '60%',
      data: Object.entries(statsData.value.statusStats).map(([name, value]) => ({
        name,
        value,
        itemStyle: {
          color: getStatusColor(name)
        }
      }))
    }
  ]
}))

// 获取建筑类型颜色
const getTypeColor = (type: string): string => {
  const colorMap: Record<string, string> = {
    '教学楼': '#1890FF',
    '实验楼': '#52C41A',
    '办公楼': '#FA8C16',
    '宿舍楼': '#722ED1',
    '图书馆': '#13C2C2',
    '体育馆': '#EB2F96',
    '食堂': '#F5222D'
  }
  return colorMap[type] || '#8C8C8C'
}

// 获取状态颜色
const getStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    '正常': '#52C41A',
    '维修': '#FA8C16',
    '停用': '#F5222D'
  }
  return colorMap[status] || '#8C8C8C'
}

// 楼层分布统计图表配置
const floorDistributionChartOptions = computed<EChartsOption>(() => ({
  title: {
    text: '楼层分布统计',
    left: 'center',
    top: 20,
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: Object.keys(statsData.value.floorStats),
    axisTick: {
      alignWithLabel: true
    }
  },
  series: [
    {
      name: '建筑数量',
      type: 'bar',
      barWidth: '60%',
      data: Object.entries(statsData.value.floorStats).map(([name, value]) => ({
        name,
        value,
        itemStyle: {
          color: getFloorColor(name)
        }
      }))
    }
  ]
}))

// 获取楼层范围颜色
const getFloorColor = (range: string): string => {
  const colorMap: Record<string, string> = {
    '1-3层': '#1890FF',
    '4-6层': '#52C41A',
    '7-10层': '#FA8C16',
    '10层以上': '#F5222D'
  }
  return colorMap[range] || '#8C8C8C'
}

/** 计算统计数据 */
const calculateStats = () => {
  const buildings = list.value

  // 总数量
  statsData.value.totalCount = buildings.length

  // 建筑类型统计
  const typeStats: Record<string, number> = {}
  buildings.forEach((building: Building) => {
    const type = building.buildingType || '未知'
    typeStats[type] = (typeStats[type] || 0) + 1
  })
  statsData.value.buildingTypeStats = typeStats

  // 状态统计
  const statusStats: Record<string, number> = {
    '正常': 0,
    '维修': 0,
    '停用': 0
  }
  buildings.forEach((building: Building) => {
    switch(building.status) {
      case 0:
        statusStats['正常']++
        break
      case 1:
        statusStats['维修']++
        break
      case 2:
        statusStats['停用']++
        break
    }
  })
  statsData.value.statusStats = statusStats

  // 楼层分布统计
  const floorStats: Record<string, number> = {
    '1-3层': 0,
    '4-6层': 0,
    '7-10层': 0,
    '10层以上': 0
  }
  let totalFloors = 0
  buildings.forEach((building: Building) => {
    const floors = building.floorCount || 0
    totalFloors += floors

    if (floors >= 1 && floors <= 3) {
      floorStats['1-3层']++
    } else if (floors >= 4 && floors <= 6) {
      floorStats['4-6层']++
    } else if (floors >= 7 && floors <= 10) {
      floorStats['7-10层']++
    } else if (floors > 10) {
      floorStats['10层以上']++
    }
  })
  statsData.value.floorStats = floorStats

  // 平均楼层数
  statsData.value.averageFloors = buildings.length > 0 ? Math.round(totalFloors / buildings.length * 10) / 10 : 0
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.building-card {
  height: 200px;
  transition: all 0.3s ease;
}

.building-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.building-card .el-card__body {
  height: 100%;
  padding: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .building-card {
    height: auto;
    min-height: 180px;
  }
}
</style>